import sys
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from cache import cache
import logging


def get_ip_proxies_juliang(url):
    """巨量IP"""
    resp = requests.get(url)
    resp_json = resp.json()
    if resp_json.get('code') == 200:
        return resp_json.get('data', {}).get('proxy_list', [None])[0]
    raise Exception('请检查IP链接是否失效')


def get_ip_proxies1(url):
    """花生IP"""
    resp = requests.get(url)
    resp_json = resp.json()
    print(resp.json())
    if resp_json.get('status') == "0":
        result = resp_json.get('list', [{}])[0]
        if result:
            ip, port = result.get('sever'), result.get('port')
            return f'{ip}:{port}'
    raise Exception('请检查IP链接是否失效')


def get_ip_proxies(url):
    """海外IP"""
    resp = requests.get(url)
    resp_json = resp.json()
    print(resp.json())
    if resp_json.get('code') == 200:
        result = resp_json.get('data', {}).get('list', '')[0]
        if result:
            return result


class Discussion:
    """评论"""

    def __init__(self, url, id=None, proxy=None):
        options = Options()
        options.add_argument("--disable-blink-features")
        options.add_argument("--window-size=1920,1080")
        options.add_argument("--disable-extensions")
        # options.add_argument("--headless")
        options.add_argument("--disable-gpu")
        options.add_argument("--disable-software-rasterizer")
        options.add_argument('--no-sandbox')
        options.add_argument('--ignore-certificate-errors')
        options.add_argument('--allow-running-insecure-content')
        options.add_argument("blink-settings=imagesEnabled=false")
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_argument(
            '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36')
        # options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36')
        # option.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36')
        if proxy:
            options.add_argument(f'--proxy-server={proxy}')

        # options.page_load_strategy = 'none'
        driver = webdriver.Chrome(options=options)

        self.driver = driver
        self.url = url
        self.id = id

    def like_(self):
        try:
            self.driver.get(self.url)
            try:
                form = self.driver.find_element(By.CLASS_NAME, 'form-alert-close-icon')
                if form:
                    form.click()
            except Exception as e:
                pass

            if self.id:
                element = self.driver.find_element(By.ID, self.id)
                button = element.find_element(By.CLASS_NAME, 'upvote-icon')
            else:
                button = self.driver.find_element(By.CLASS_NAME, 'upvote-icon')

            if button:
                action = ActionChains(self.driver)
                action.move_to_element(button)
                button.click()
                # time.sleep(5)
                return 1

        except Exception as e:
            logging.warning(e.msg)
            return
        finally:
            self.driver.close()



    def metoo(self):
        try:
            self.driver.get(self.url)
            try:
                form = self.driver.find_element(By.CLASS_NAME, 'form-alert-close-icon')
                if form:
                    form.click()
            except Exception as e:
                pass

            if self.id:
                element = self.driver.find_element(By.ID, self.id)
                button = element.find_element(By.CLASS_NAME, 'me-too ')
            else:
                button = self.driver.find_element(By.CLASS_NAME, 'me-too')

            if button:
                action = ActionChains(self.driver)
                action.move_to_element(button)
                button.click()
                # time.sleep(5)
                return 1

        except Exception as e:
            logging.warning(e.msg)
            return
        finally:
            self.driver.close()


def run_like(url, aid, times, job_id=None):
    """执行"""
    ip_url = cache.get('ip_pool')
    progress = '进行中'
    count = 0
    total = 0

    try:
        if job_id:
            job = cache.get(job_id)
            job['progress'] = progress
            cache.set(job_id, job, 0)

        while True:
            total += 1
            proxy = get_ip_proxies(ip_url)
            print(proxy, flush=True)
            discussion = Discussion(url, aid, proxy=proxy)
            is_success = discussion.like_()
            if is_success:
                count += 1
                status = '成功'

            else:
                status = '失败'

            if job_id:
                job['total'] = total
                job['count'] = count
                job['detail'].append({'proxy': proxy, 'status': status})
                cache.set(job_id, job, 0)

            if count >= times:
                print(f'times: {count}', flush=True)
                break

            if total >= times:
                print(f'times: {total}_{count}', flush=True)
                break

        progress = '完成'

    except Exception as e:
        logging.warning(e)
        if job_id:
            job['detail'].append({'proxy': '-', 'status': e})

        progress = f'未完成'

    finally:
        if job_id:
            job['progress'] = progress
            job['count'] = count
            cache.set(job_id, job, 0)


def run_metoo(url, aid, times, job_id=None):
    """执行"""
    ip_url = cache.get('ip_pool')
    progress = '进行中'
    count = 0
    total = 0

    try:
        if job_id:
            job = cache.get(job_id)
            job['progress'] = progress
            cache.set(job_id, job, 0)

        while True:
            total += 1
            proxy = get_ip_proxies(ip_url)
            print(proxy, flush=True)
            discussion = Discussion(url, aid, proxy=proxy)
            is_success = discussion.metoo()
            if is_success:
                count += 1
                status = '成功'

            else:
                status = '失败'

            if job_id:
                job['total'] = total
                job['count'] = count
                job['detail'].append({'proxy': proxy, 'status': status})
                cache.set(job_id, job, 0)

            if count >= times:
                print(f'times: {count}', flush=True)
                break

            if total >= times:
                print(f'times: {total}_{count}', flush=True)
                break
        progress = '完成'

    except Exception as e:
        logging.warning(e)
        if job_id:
            job['detail'].append({'proxy': '-', 'status': e})

        progress = f'未完成'

    finally:
        if job_id:
            job['progress'] = progress
            job['count'] = count
            cache.set(job_id, job, 0)


if __name__ == '__main__':
    v = sys.argv
    url, aid, times = v[1], v[2], 1
    if aid == '0':
        aid = None
    if len(v) >= 4:
        if v[3] == 'metoo':
            run_metoo(url, aid, times)

    run_like(url, aid, times)
